#!/usr/bin/env python

import re
import os
import sys
import time
import shutil
from optparse import OptionParser

usage = "usage: %prog -d <directory>"
parser = OptionParser(usage)
parser.add_option("-d", "--directory", dest = "work_dir", default = "./", help = "directory")
parser.add_option("-p", "--period", dest = "period", default = 30, help = "how many days for backup? default: 30 days")
(option, args) = parser.parse_args()

work_dir = os.path.abspath(option.work_dir)

if not os.path.isdir(work_dir):
    print "directory not available"
    sys.exit(1)

fulldump_dir = work_dir + "/backup/fulldump/"
binlog_dir = work_dir + "/backup/"
archivement_dir = work_dir + "/archivement/"
binlog_files = []
mysqlbin_dir = "/usr/local/mysql/bin/"

# 1 day 86400 seconds
p = int(option.period) * 86400
p =float(p)
t = time.time() - p  #earlier files will be archived

def Archive_fulldump_file():
    try:
        fulldump_files_all = os.listdir(fulldump_dir)
    except OSError:
        print "Error: not in correct directory!"
        sys.exit(1)
    fulldump_files = []
    log_files = []

    for file in fulldump_files_all:
        matchFulldump = re.match(r'mysql_backup.*[.]sql[.]gz', file)
        matchLog = re.match(r'mysql_backup.*[.]log', file)
        if matchFulldump or matchLog:
            file = fulldump_dir + file
            time_file = os.path.getmtime(file)
            if t >= time_file:
                if matchFulldump:
                    fulldump_files.append(file)
                if matchLog:
                    log_files.append(file)

    if fulldump_files == []:
        print "could not find fulldump files"
    else:
        for fulldump in fulldump_files:
            try:
                shutil.move(fulldump, archivement_dir)
                print "fulldump files archived"
            except Exception,e:
                print e
    if log_files == []:
        print "could not find log files"
    else:
        for log in log_files:
            try:
                os.remove(log)
                print "log files removed"
            except Exception, e:
                print e


def Remove_binlog_files():
    try:
        binlog_files_all = os.listdir(binlog_dir)
    except OSError:
        print "Error: not in correct directory!"
        sys.exit(1)
    binlog_files = []

    for file in binlog_files_all:
        matchFile = re.match(r'mysql-bin.\d{6}$', file)
        if matchFile:
            file = binlog_dir + file
            time_file = os.path.getmtime(file)
            if t + 86400 >= time_file:
                binlog_files.append(file)
    if binlog_files == []:
        print "could not find binlog files"
    else:
        for file in binlog_files:
            try:
                os.remove(file)
                print "binlog files removed"
            except Exception, e:
                print e


if __name__ == '__main__':
    print "keep %s days fulldump" % option.period
    Archive_fulldump_file()
    Remove_binlog_files()
